package net.goutalk.glcs.module.workflow.controller;

import cn.hutool.core.bean.BeanUtil;
import com.github.yulichang.toolkit.MPJWrappers;
import net.goutalk.glcs.common.constant.GlobalConstant;
import net.goutalk.glcs.common.model.result.R;
import net.goutalk.glcs.common.utils.VoToColumnUtil;
import net.goutalk.glcs.module.organization.entity.User;
import net.goutalk.glcs.module.workflow.dto.HistoryChangeDto;
import net.goutalk.glcs.module.workflow.entity.WorkflowSchemaHistory;
import net.goutalk.glcs.module.workflow.service.IWorkflowSchemaHistoryService;
import net.goutalk.glcs.module.workflow.vo.SchemaHistoryListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 流程模板历史记录表 前端控制器
 * </p>
 *
 * @author tanyujie
 * @since 2022-11-16
 */
@RestController
@RequestMapping(GlobalConstant.WORKFLOW_MODULE_PREFIX + "/schema-history")
@Api(value = GlobalConstant.WORKFLOW_MODULE_PREFIX + "/schema-history", tags = "流程模板历史记录接口")
@AllArgsConstructor
public class WorkflowSchemaHistoryController {

    private final IWorkflowSchemaHistoryService workflowSchemaHistoryService;


    @GetMapping("/list")
    @ApiOperation(value = "流程列表（分页）")
    public R list(@RequestParam Long schemaId) {
        List<SchemaHistoryListVo> schemaHistoryListVos = workflowSchemaHistoryService.selectJoinList(SchemaHistoryListVo.class,
                MPJWrappers.<WorkflowSchemaHistory>lambdaJoin()
                        .eq(WorkflowSchemaHistory::getSchemaId, schemaId)
                        .select(WorkflowSchemaHistory::getId)
                        .select(WorkflowSchemaHistory.class, x -> VoToColumnUtil.fieldsToColumns(SchemaHistoryListVo.class).contains(x.getProperty()))
                        .selectAs(User::getName, SchemaHistoryListVo::getCreateUserName)
                        .leftJoin(User.class, User::getId, WorkflowSchemaHistory::getCreateUserId)
                        .orderByAsc(WorkflowSchemaHistory::getVersion)
        );

        List<SchemaHistoryListVo> listVos = BeanUtil.copyToList(schemaHistoryListVos, SchemaHistoryListVo.class);
        return R.ok(listVos);
    }

    @PutMapping("/set-current")
    @ApiOperation(value = "更新到此版本")
    public R change(@Valid @RequestBody HistoryChangeDto dto) {

        return R.ok(workflowSchemaHistoryService.change(dto));
    }

    @PutMapping("/processChanges")
    @ApiOperation(value = "新流程变更")
    public R processChanges(@Valid @RequestBody HistoryChangeDto dto) {
        return R.ok(workflowSchemaHistoryService.change(dto));
    }

    @GetMapping("/preview")
    @ApiOperation(value = "历史记录的xml")
    public R preview(@RequestParam String historyId){
        WorkflowSchemaHistory history = workflowSchemaHistoryService.getById(historyId);
        return R.ok(history.getXmlContent());
    }
}
